import json
import threading
import pika
from concurrent.futures import ThreadPoolExecutor
from dependency_injector import containers, providers
from crewai import Agent

class Configs(containers.DeclarativeContainer):
    rabbitmq_url = providers.Configuration("rabbitmq_url")
    queue_name = providers.Configuration("queue_name")
    thread_pool_size = providers.Configuration("thread_pool_size")

class Services(containers.DeclarativeContainer):
    config = providers.Container(Configs)
    executor = providers.Singleton(ThreadPoolExecutor, max_workers=config.thread_pool_size)

class RabbitMQListener:
    def __init__(self, config, executor):
        self.config = config
        self.executor = executor
        self.connection = pika.BlockingConnection(pika.URLParameters(config.rabbitmq_url()))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=config.queue_name(), durable=True)

    def on_message(self, ch, method, properties, body):
        message = json.loads(body)
        task_description = message.get("task_description")
        print(f"Received task: {task_description}")
        self.executor.submit(self.process_task, task_description)

    def process_task(self, task_description):
        from crewai import LLM
        import os
        url = os.getenv("DS_BASE_URL")
        key = os.getenv("DS_API_KEY")
        deepseek_r1 = LLM(
            model="deepseek-chat",
            temperature=0,
            base_url= url,
            api_key=key
        )
        agent = Agent(task_description,llm=deepseek_r1)  # 假设 crawai.Agent 以任务描述初始化
        result = agent.run()
        print(f"Task Completed: {result}")

    def start_listening(self):
        self.channel.basic_consume(queue=self.config.queue_name(), on_message_callback=self.on_message, auto_ack=True)
        print("Waiting for messages...")
        self.channel.start_consuming()

if __name__ == "__main__":
    container = Services()
    container.config.rabbitmq_url.override("amqp://guest:guest@localhost:5672/")
    container.config.queue_name.override("taskQueue")
    container.config.thread_pool_size.override(10)

    listener = RabbitMQListener(container.config, container.executor())
    thread = threading.Thread(target=listener.start_listening, daemon=True)
    thread.start()
    thread.join()
